/**
 * 2014-8-28下午11:55:47
 */
package com.shjy.driver.bordcast;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.shjy.driver.R;
import com.shjy.driver.activity.DetailActivity;
import com.shjy.driver.adapter.SpeakTask;
import com.shjy.driver.jg.JGReceiver;
import com.shjy.driver.service.LocationService;
import com.shjy.driver.util.AppUtil;
import com.shjy.driver.util.Const;
import com.shjy.driver.xf.XFUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: MyBroadcastReceiver
 * @package com.mayi.bordcast
 * @author mayi
 * @date 2014-8-28 下午11:55:47
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @version 1.0
 *
 */

public class MyBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(final Context context, Intent intent) {
		if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
			// 检查Service状态
			boolean isServiceRunning = false;
			ActivityManager manager = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			for (RunningServiceInfo service : manager
					.getRunningServices(Integer.MAX_VALUE)) {
				if ("com.shjy.driver.service.LocationService".equals(service.service
						.getClassName()))// Service的类名
				{
					isServiceRunning = true;
					Log.e("mayi", "http   runing...");
				}

			}
			if (!isServiceRunning) {
				try{
					initData("restart Location service in MyBroadcastReceiver class");
				}catch (Exception ex){
					ex.printStackTrace();
				}
				Intent i = new Intent(context, LocationService.class);
				context.startService(i);
			}

//			try{
//				String url = Const.DOMAIN + "capital/driver/messageFlag.htm";
//				SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
//				final String driverUuid = sharedPreferences.getString(Const.KEY_TOKEN, "");
//				RequestQueue requestQueue = Volley.newRequestQueue(context);
//
//				StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
//					@Override
//					public void onResponse(String s) {
//						Log.d("", "onResponse " + s);
//						if(s!=null && s.length()>8) {
//							try {
//								JSONObject jsonObject = new JSONObject(s);
//								String message = jsonObject.getString("message");
//								message = "交运便捷系统消息："+message;
//								if (!TextUtils.isEmpty(message)) {
//									playDing(context);
//
//									Timer timer = new Timer();
//									timer.schedule(new SpeakTask(context,message), 6000);//3秒后执行TimeTask的run方法
//									//XFUtil.speak(context, message);
//								}
//							}catch (Exception ex){
//								ex.printStackTrace();
//							}
//						}
//					}
//				}, new Response.ErrorListener() {
//					@Override
//					public void onErrorResponse(VolleyError volleyError) {
//						Log.d("", "onErrorResponse " + volleyError.getMessage());
//					}
//				}) {
//					@Override
//					protected Map<String, String> getParams() throws AuthFailureError {
//						Map<String, String> map = new HashMap<String, String>();
//						try {
//							map.put("driverUuid", driverUuid);
//						}catch (Exception ex){
//							ex.printStackTrace();
//						}
//						//Log.d(TAG, "getParams " + map);
//						return map;
//					}
//				};
//
//				requestQueue.add(stringRequest);
//			}catch (Exception ex){
//				ex.printStackTrace();
//			}
		}
	}

	public void playDing(Context mContext) {
		NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		Uri ringUri = Uri.parse("android.resource://" + mContext.getPackageName() + "/"+ R.raw.ding);//RingtoneManager.getDefaultUri(ringType);
		Notification notification = new NotificationCompat.Builder(mContext)
				.setTicker("开始接单").setSound(ringUri)
				.setContentTitle("开始接单").setContentText("开始接单").setSound(ringUri).build();
		Ringtone r = RingtoneManager.getRingtone(mContext, ringUri);
		r.play();
	}

	private static void initData(String text) {
		String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.shjy.driver/files/Download/";
		String fileName = "";
		try {
			fileName = "log-"+formatDate(new Date())+".txt";
		}catch (Exception ex){
			ex.printStackTrace();
		}

		writeTxtToFile(text, filePath, fileName);
	}

	private static  String formatDate(Date date) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	// 将字符串写入到文本文件中
	public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
		//生成文件夹之后，再生成文件，不然会出错
		makeFilePath(filePath, fileName);

		String strFilePath = filePath+fileName;
		// 每次写入时，都换行写
		String strContent = strcontent + "\r\n";
		try {
			File file = new File(strFilePath);
			if (!file.exists()) {
				Log.d("TestFile", "Create the file:" + strFilePath);
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			RandomAccessFile raf = new RandomAccessFile(file, "rwd");
			raf.seek(file.length());
			raf.write(strContent.getBytes());
			raf.close();
		} catch (Exception e) {
			Log.e("TestFile", "Error on write File:" + e);
		}
	}

	// 生成文件
	public static File makeFilePath(String filePath, String fileName) {
		File file = null;
		makeRootDirectory(filePath);
		try {
			file = new File(filePath + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	// 生成文件夹
	public static void makeRootDirectory(String filePath) {
		File file = null;
		try {
			file = new File(filePath);
			if (!file.exists()) {
				file.mkdir();
			}
		} catch (Exception e) {
			Log.i("error:", e+"");
		}
	}

}
